package ar.com.cooker.dao.impl;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import ar.com.cooker.dao.RecipeDao;
import ar.com.cooker.model.Recipe;

@Repository
@Transactional
public class RecipeDaoImpl implements RecipeDao {

	private EntityManager entityManager;

	@Override
	public void delete(Integer id) {
		Recipe r = getEntityManager().find(Recipe.class, id);
		getEntityManager().remove(r);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Recipe> findAll() {
		Query q = getEntityManager().createQuery("FROM Recipe r");
		return (List<Recipe>) q.getResultList();
	}

	@Override
	public Recipe findById(Integer id) {
		Recipe r = getEntityManager().find(Recipe.class, id);
		return r;
	}

	@Override
	public void save(Recipe t) {
		getEntityManager().persist(t);
	}

	@Override
	public void update(Recipe t) throws DataAccessException {
		if (t.getId() == null) {
			// determinar la excepcion.
		} else {
			getEntityManager().merge(t);
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Recipe> findAllRecipeByName(String key) {
		Query query = getEntityManager().createQuery(
				"SELECT r " + "FROM Recipe r WHERE r.tittle LIKE :name")
				.setParameter("name", "%" + key + "%");
		return (List<Recipe>) query.getResultList();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Recipe> findAllRecipeByIngredientName(String nameIngredient) {
		Query query = getEntityManager()
				.createQuery(
						"SELECT r "
								+ "FROM Recipe r,RecipeIngredient ri, Ingredient i WHERE ri.id.ingredient.id = i.id "
								+ "AND ri.id.recipe.id = r.id "
								+ "AND i.name LIKE :name").setParameter("name",
						"%" + nameIngredient + "%");
		return query.getResultList();
	}

	@PersistenceContext
	public void setEntityManager(EntityManager entityManager) {
		this.entityManager = entityManager;
	}

	public EntityManager getEntityManager() {
		return entityManager;
	}

}
